package com.speciality.demo.demos.web;


import com.speciality.demo.demos.entity.User;
import com.speciality.demo.demos.result.Result;
import com.speciality.demo.demos.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Controller
public class UserController {
    @Autowired
    private UserService userService;

    @PostMapping("/addUser")
    @ResponseBody
    public Result  add(@RequestBody User user){
        User user1 = userService.getByUsername(user.getUsername());
        if (user1!=null){

            return Result.fail();
        }
        userService.add(user);
        return Result.ok();
    }
    // ========== 新增：表单登录（用于页面跳转） ==========
    @PostMapping("/login")
    public String loginForm(
            @ModelAttribute User user,  // 接收表单参数
            HttpSession session,       // 会话对象
            Model model                // 传递错误信息
    ) {
        System.out.println("表单登录参数：" + user);
        User loginUser = userService.login(user); // 复用原有加密逻辑

        if (loginUser != null) {
            session.setAttribute("user", loginUser); // 会话存储用户
            return "redirect:/index.html"; // 跳转到主页面
        } else {
            model.addAttribute("error", "用户名或密码错误");
            return "login"; // 跳转回登录页（需确保 login.html 可被视图解析器访问，或直接返回静态页）
        }
    }

    // ========== 保留：原有 JSON 登录接口（供 AJAX 调用） ==========
    @PostMapping("/api/login")
    @ResponseBody
    public Result loginApi(@RequestBody User user) {
        User loginUser = userService.login(user);
        return loginUser != null ? Result.ok() : Result.fail("用户名或密码错误");
    }
    @GetMapping("/allUser")
    public Result allUser(){
        List<User> users = userService.allUser();
        System.out.println(users);
        return Result.ok();
    }
}
